package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentInfoService;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.order.utils.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    //根据订单号下单，生成支付链接
    @Override
    public Map createNative(Long orderId) {
        //1.根据订单号查询订单信息
        OrderInfo orderInfo = orderInfoService.getOderInfo(orderId);

        //2.订单信息添加支付记录表（状态：支付中）
        paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

        try {
            //3.封装微信二维码生成接口需要数据
            Map paramMap = new HashMap();
            //公众号id
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            //商户号
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            //传递随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //微信扫码支付二维码，微信显示内容
            Date reserveDate = orderInfo.getReserveDate();
            String reserveDateString  = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊" + orderInfo.getHosname() + "-" + orderInfo.getDepname();
            paramMap.put("body",body);
            //订单交易号
            paramMap.put("out_trade_no",orderInfo.getOutTradeNo());
            //支付金额
            //paramMap.put("total_fee", orderInfo.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//TODO  为了测试 0.01
            //客户端ip地址
            paramMap.put("spbill_create_ip", "127.0.0.1");
            //回调地址
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            //二维码类型  NATIVE
            paramMap.put("trade_type", "NATIVE");

            //4.使用httpclient请求微信二维码生成接口，返回需要数据
            //设置请求路径
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置向路径传递参数，参数需要xml格式，并且使用商户key编码
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            //设置支持https
            client.setHttps(true);
            //发送请求
            client.post();

            //微信接口请求之后，返回数据，格式xml
            String xml = client.getContent();
            System.out.println("xml"  + xml);

            //把返回xml转换为map集合
            //wxMap集合包含微信支付二维码地址 code_url
            Map<String, String> wxMap = WXPayUtil.xmlToMap(xml);

            //把页面需要数据返回
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", wxMap.get("result_code")); //状态码
            //  weixin://9887-443dde
            map.put("codeUrl", wxMap.get("code_url"));  //微信支付二维码地址

            return map;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //根据订单号去微信第三方查询支付状态
    @Override
    public Map<String, String> queryPayStatus(Long orderId, String paymentType) {
       try {
           OrderInfo orderInfo = orderInfoService.getById(orderId);
           //1.根据订单号查询订单状态
           OrderInfo oderInfo = orderInfoService.getOderInfo(orderId);

           //2 封装微信接口需要参数
           Map paramMap = new HashMap<>();
           paramMap.put("appid", ConstantPropertiesUtils.APPID);
           paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
           paramMap.put("out_trade_no", orderInfo.getOutTradeNo());//交易号
           paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

           //3.使用httpClient调用微信查询支付状态接口
           HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
           client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
           client.setHttps(true);
           client.post();

           //4.得到微信支付状态查询接口返回数据
           String xml = client.getContent();
           Map<String, String> map = WXPayUtil.xmlToMap(xml);
           System.out.println("支付状态返回：" + map);
           return map;
       }catch (Exception e){
           e.printStackTrace();
           return null;
       }
    }

    //退款方法
    @Override
    public Boolean refund(Long orderId) {
        //1.根据订单号查询订单数据支付记录（使用两个值：交易号和trade_no）
        PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(orderId);
        if(paymentInfo == null || paymentInfo.getPaymentStatus().equals(PaymentStatusEnum.UNPAID.getStatus())){
            return true;
        }

        //2 添加退款记录到退款记录表(退款中)
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        if(refundInfo.getRefundStatus().equals(RefundStatusEnum.REFUND.getStatus())){
            return true;
        }

        //3 封装微信退款接口需要参数
        Map<String,String> paramMap = new HashMap<>(8);
        paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
        paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
        //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //TODO 为了测试 0.01
        paramMap.put("total_fee","1");
        paramMap.put("refund_fee","1");

        try{
            //4 使用httpclient请求微信退款接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            //是否使用证书
            client.setCert(true);
            //证书密码  商户号
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();

            //返回结果
            String xml = client.getContent();
            System.out.println("退款之后返回数据：" + xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //返回成功
            if(null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))){
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                //已经退款
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
